package com.ybkj.o2o.sales.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zhyu
 * @date 2019/5/17 10:07
 * desc:
 */
@Aspect
@Component
public class LoggerAop {

    private final static Logger logger = LoggerFactory.getLogger(LoggerAop.class);

    @Pointcut("execution(public * com.ybkj.o2o.sales.*.res.*.*(..))")
    public void pointCutApi() {

    }

    @Before("pointCutApi()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        String req = null;
        try{
            req = JSONObject.toJSONString(joinPoint.getArgs());
        }catch (Exception e){

        }
        logger.info("URL:{} |METHOD:{} |REQ: {} ",request.getRequestURL().toString(),request.getMethod(),req);    }

    @AfterReturning(returning = "ret", pointcut = "pointCutApi()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("RESPONSE : " + ret);
    }

}
